<template>
    <div class="top">
        <h2>
            {{ route.params.id ? '编辑' : '新增' }}图书
        </h2>
    </div>
    <div class="content">
        <form>
            <table>
                <tbody>
                    <tr>
                        <td>书名</td>
                        <td>
                            <input type="text" v-model="data.name">
                        </td>
                    </tr>
                    <tr>
                        <td>作者</td>
                        <td>
                            <input type="text" v-model="data.author">
                        </td>
                    </tr>
                    <tr>
                        <td><input type="button" :value="`确认${route.params.id ? '编辑' : '新增'}`" @click="yes"></td>
                        <td><input type="button" :value="`取消${route.params.id ? '编辑' : '新增'}`" @click="no"></td>
                    </tr>
                </tbody>
            </table>
        </form>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { bookAdd, bookOne, bookUpdate } from '@/bookApi/bookApi'

let route = useRoute()
let router = useRouter()
let data = ref({
    name: '',
    author: ''
})


async function yes() {
    if (route.params.id) {
        //编辑
        await bookUpdate(route.params.id, data.value);
    } else {
        await bookAdd(data.value)
    }
    router.push('/')
}

function no() {
    router.push('/')
}

onMounted(async () => {
    if (route.params.id) {
        data.value = await bookOne(route.params.id)
    }
})


</script>